package com.example.dicomviewer;

import android.graphics.Bitmap;
import android.util.Log;

import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.Tag;
import org.dcm4che3.io.DicomInputStream;

import java.io.File;

import olddcm4che3.android.Raster;
import olddcm4che3.android.RasterUtil;
import olddcm4che3.android.imageio.dicom.DicomImageReader;

/*
 * 此类两个功能
 * 1. 读取文件信息(传入真实路径,返回DicomInfo类型的文件信息
 * 2. 读取文件(传入真实路径,返回BitMap类型的图像数据
 * */
public class DicomFileReader {

    /**
     * 读取文件数据
     */
    public static DicomInfo readFileInfo(String filePath) {
        DicomImageReader dr = new DicomImageReader();
        try {
            File file = new File(filePath);
            //dcm文件输入流
            DicomInputStream dcmInputStream = new DicomInputStream(file);
            //属性对象
            Attributes attrs = dcmInputStream.readDataset(-1, -1);
            //输出所有属性信息
//            Log.e("TAG", "输出所有属性信息1:" + attrs);
            return new DicomInfo(attrs);
        } catch (Exception e) {
            Log.e("TAG", "" + e);
        }
        return null;
    }

    public static Bitmap readFileBitMap(String filePath) {
        DicomImageReader dr = new DicomImageReader();
        try {
            File file = new File(filePath);
            //dcm文件输入流
            DicomInputStream dcmInputStream = new DicomInputStream(file);
            //属性对象
            Attributes attrs = dcmInputStream.readDataset(-1, -1);
            //获取行
            int row = attrs.getInt(Tag.Rows, 1);
            //获取列
            int columns = attrs.getInt(Tag.Columns, 1);
            //窗宽窗位 (这里应该指的是 显示像素值的范围, https://www.it1352.com/900230.html
            /*How to calculate the pixels to display using the window center/width:
              lowest_visible_value = window_center - window_width / 2
              highest_visible_value = window_center + window_width / 2
            *
            * */
            float win_center = attrs.getFloat(Tag.WindowCenter, 1);
            float win_width = attrs.getFloat(Tag.WindowWidth, 1);
            dr.open(file);
            Raster raster = dr.applyWindowCenter(0, (int) win_width, (int) win_center);
            Bitmap bmp = RasterUtil.gray8ToBitmap(columns, row, raster.getByteData());
//            iv.setImageBitmap(bmp); //显示图片
            return bmp;
        } catch (Exception e) {
            Log.e("TAG", "" + e);
        }
        return null;
    }

}
